<?php

namespace plugin\admin\app\service\v1;

use Illuminate\Database\Connection;
use plugin\admin\app\common\Util;
use plugin\admin\app\constant\v1\CommonConstant;
use support\exception\BusinessException;

/**
 * 返佣服务类
 **/
class CommissionService
{

    /**
     * 返佣
     *
     * @param array $params
     **/
    public static function index($params)
    {
        $config = OptionService::getConfig('commission');
        $commission_type = $config['commission_type'];
        $commission_level = $config['commission_level'] ?? 0;
        if ($commission_level <= 0) {
            throw new BusinessException('返佣级数为零！');
        }
        if ($params['commission_type'] == CommonConstant::DEFAULT_1) {
            if ($commission_type !== CommonConstant::DEFAULT_1) {
                throw new BusinessException('未开启' . CommonConstant::get_commission_type_list()[$params['commission_type']] . '！');
            }
            self::order($params,$commission_level);
        }
        if ($params['commission_type'] == CommonConstant::DEFAULT_2) {
            if ($commission_type !== CommonConstant::DEFAULT_2) {
                throw new BusinessException('未开启' . CommonConstant::get_commission_type_list()[$params['commission_type']] . '！');
            }
            self::recharge($params);
        }
        return true;
    }

    /**
     * 消费返佣
     *
     * @param array $params
     * @param integer $commission_level
     * @return bool
     **/
    public static function order($params,$commission_level)
    {
        list($commissionType, $type, $moneyLogId) = array_values($params);

        $db = Util::db();

        // 1. 余额变动记录
        $moneyLogInfo = self::getMoneyLogInfo($db, $moneyLogId);

        $userId = $moneyLogInfo->user_id;
        $lineId = $moneyLogInfo->line_id;
        $duration = $moneyLogInfo->duration;

        // 2. 用户权限和价格
        $userExtendInfo = self::getUserExtendInfo($db, $userId, $lineId, $duration);
        $currentPrice = $userExtendInfo->{$duration} ?? 0;
        if ($currentPrice <= 0) {
            throw new BusinessException('当前用户卡价格无效！');
        }

        // 3. 获取上级用户链
        $superiors = self::getSuperiors($db, $userId,$commission_level);
        if (empty($superiors)) {
            throw new BusinessException('无上级代理，无需返佣！');
        }

        // 4.处理数据
        $insertLogData = self::processSuperiors($db, $type, $moneyLogInfo, $currentPrice, $superiors);

        // 5.执行操作
        self::Execute($db, $moneyLogInfo, $insertLogData);
        return true;
    }

    /**
     * 充值返佣
     *
     * @param array $params
     * @return bool
     **/
    public static function recharge($params)
    {
        list($commissionType, $type, $moneyLogId) = array_values($params);
        return true;
    }


    /**
     * 余额变动记录
     *
     * @param Connection $db
     * @param integer $moneyLogId
     * @return mixed
     **/
    public static function getMoneyLogInfo($db, $moneyLogId)
    {
        $moneyLogInfo = $db->table('wa_v1_user_money_log')
            ->where('deleted', CommonConstant::DELETE_0)
            ->where('id', $moneyLogId)
            ->select(['user_id', 'user_name', 'money', 'memo', 'order_id','order_node_ids', 'line_id', 'duration', 'commission_status'])
            ->first();
        if (!$moneyLogInfo) {
            throw new BusinessException('余额变动记录不存在！');
        }
        if ($moneyLogInfo->commission_status == CommonConstant::DEFAULT_1) {
            throw new BusinessException('返佣状态已改变，不能重复返佣！');
        }
        return $moneyLogInfo;
    }

    /**
     * 用户权限和价格
     *
     * @param Connection $db
     * @param integer $userId
     * @param integer $lineId
     * @param string $duration
     * @return mixed
     **/
    public static function getUserExtendInfo($db, $userId, $lineId, $duration)
    {
        $userExtendInfo = $db->table('wa_v1_user_extend')
            ->where('user_id', $userId)
            ->where('line_id', $lineId)
            ->select(['id', $duration])
            ->first();
        if (!$userExtendInfo) {
            throw new BusinessException('用户价格配置不存在！');
        }
        return $userExtendInfo;
    }

    /**
     * 获取上级用户链
     *
     * @param Connection $db
     * @param integer $userId
     * @param integer $commission_level
     * @return array
     */
    public static function getSuperiors($db, $userId,$commission_level)
    {
        $superiors = [];
        $currentId = $userId;
        $maxLevel = $commission_level;
        for ($i = 0; $i < $maxLevel; $i++) {
            if (!$currentId) {
                break;
            }
            $parent = (array)$db->table('wa_admins')
                ->join('wa_admins as parent', 'wa_admins.invitation_id', '=', 'parent.id')
                ->where('wa_admins.id', $currentId)
                ->select(['parent.id', 'parent.username', 'parent.invitation_id'])
                ->first();
            if (!$parent || empty($parent['id'])) {
                break;
            }

            $superiors[] = $parent;
            $currentId = $parent['id'];
        }
        return $superiors;
    }

    /**
     * 处理数据
     *
     * @return array
     **/
    public static function processSuperiors($db, $type, $moneyLogInfo, $currentPrice, $superiors)
    {
        $superiorsColumn = array_column($superiors, null, 'id');
        $parentIds = array_keys($superiorsColumn);
        $parentExtendData = $db->table('wa_v1_user_extend')
            ->whereIn('user_id', $parentIds)
            ->where('line_id', $moneyLogInfo->line_id)
            ->pluck($moneyLogInfo->duration, 'user_id')
            ->toArray();
        if (!$parentExtendData) {
            throw new BusinessException('上级代理价格配置不存在，无需返佣！');
        }

        // 统计订单节点数量
        $nodeIds = array_filter(explode(',', $moneyLogInfo->order_node_ids));
        $nodeCount = count($nodeIds);

        $insertLogData = [];
        $amount = $currentPrice;
        foreach ($superiors as $key => $superior) {
            $superiorAmount = $parentExtendData[$superior['id']] ?? 0;
            if ($superiorAmount == 0) {
                break;
            }
            if ($amount <= $superiorAmount) {
                break;
            }

            // 计算返佣金额：价格差 × 节点数量
            $money = bcsub($amount,$superiorAmount,2);
            $money2 = bcmul($money,$nodeCount,2);
            $amount = $superiorAmount;

            $logData = [
                'admin_id' => $moneyLogInfo->user_id,
                'admin_name' => $moneyLogInfo->user_name,
                'user_id' => $superior['id'],
                'user_name' => $superior['username'],
                'type' => $type,
                'change_type' => CommonConstant::DEFAULT_10,
                'money' => $money2,
                'memo' => $moneyLogInfo->memo,
                'order_node_ids' => $moneyLogInfo->order_node_ids,
                'line_id' => $moneyLogInfo->line_id,
                'duration' => $moneyLogInfo->duration,
                'log_item_data'=>[],
            ];
            foreach ($nodeIds as $value) {
                $logItemData = [];
                $logItemData['item_id'] = $value;
                $logItemData['money'] = $money;
                $logData['log_item_data'][] = $logItemData;
            }
            $insertLogData[] = $logData;
        }
        return $insertLogData;
    }

    /**
     * 执行操作
     **/
    public static function execute($db, $moneyLogInfo, $insertLogData)
    {
        $db->transaction(function () use ($db, $moneyLogInfo, $insertLogData) {
            $insertLogItemData = [];
            foreach ($insertLogData as $logData) {
                // 佣金变动
                $logItemData = $logData['log_item_data'];
                unset($logData['log_item_data']);
                $logId = UserService::commission($logData, $logData['user_id'], [], ['type' => 'commission']);

                // 将每个节点项目单独添加到数组中，而不是整个数组
                foreach ($logItemData as $item) {
                    $item['log_id'] = $logId;
                    $insertLogItemData[] = $item; // 直接添加单个记录，而不是数组
                }
            }
            if($insertLogItemData){
                $db->table('wa_v1_user_commission_log_item')->insert($insertLogItemData);
            }
        });
        return true;
    }

    /**
     * 更新返佣状态
     **/
    public static function setCommissionStatus($moneyLogId, $commissionInfo)
    {
        Util::db()->table('wa_v1_user_money_log')
            ->where('id', $moneyLogId)
            ->update(['commission_status' => CommonConstant::DEFAULT_1, 'commission_info' => $commissionInfo]);
        return true;
    }

}
